﻿ using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Configuration;
using iTextSharp;
using iTextSharp.text.pdf;
using iTextSharp.text;
using iTextSharp.text.html.simpleparser;
using iTextSharp.text.html;
using System.IO;
using System.Runtime.InteropServices;
using System.Diagnostics;
using System.Data.SqlClient;

namespace CTEA_INDIA
{
    public partial class Artist_Card : System.Web.UI.Page
    {
        DataSet dsPhotosFiles = new DataSet();
        protected void Page_Load(object sender, EventArgs e)
        {
            BAL.conn.connectionString = ConfigurationManager.ConnectionStrings["CTEA"].ConnectionString;
            if (!IsPostBack)
            {

              
                populateArtistCard();
                BAL.Customers.PopulateLoc(ref cmbLocation);
                BAL.Customers.PopulateLoc(ref cmbEdtLocation);
                BAL.Customers.PopulateLocation(ref cmbSrchLoc);
            }
            if (Session["UserID"] == null)
            {
                Response.Redirect("Default.aspx");
            }


            string[] Details = BAL.Customers.GetMaxArtistCardId();

            int genVal = Details[0].ToString().Count();
            int idNo = Convert.ToInt32(Details[0]) + 1;
            string memno = "";

            if (genVal == 1)
            {
                memno = "MN00000" + idNo.ToString();
            }
            else if (genVal == 2)
            {
                memno = "MN0000" + idNo.ToString();
            }
            else if (genVal == 3)
            {
                memno = "MN000" + idNo.ToString();
            }
            else if (genVal == 4)
            {
                memno = "MN00" + idNo.ToString();
            }
            else if (genVal == 5)
            {
                memno = "MN0" + idNo.ToString();
            }
            else if (genVal == 6)
            {
                memno = "MN" + idNo.ToString();
            }

            lblArtisCardNo.Text = memno;

            //BAL.Customers.PopulateLoc(ref cmbEdtLocation);
        }

        private void bindDataList()
        {
            //dlPhotoFiles.DataSource = dsPhotosFiles;
            //dlPhotoFiles.DataKeyField = "id";
            //dlPhotoFiles.DataBind();
        }

        protected void Page_Init(object sender, EventArgs e)
        {

            if (Session["dsPhotoFiles"] == null)
            {
                this.initPhotoDS();
                Session.Add("dsPhotoFiles", dsPhotosFiles);
            }
            else
            {
                dsPhotosFiles = (DataSet)Session["dsPhotoFiles"];
            }
        }

        protected void btnUpload_Click(object sender, EventArgs e)
        {
            try
            {
                // Get the HttpFileCollection
                HttpFileCollection hfc = Request.Files;
                for (int i = 0; i < hfc.Count; i++)
                {
                    HttpPostedFile hpf = hfc[i];
                    if (hpf.ContentLength > 0)
                    {
                        hpf.SaveAs(Server.MapPath("MyFiles") + "\\" +
                          System.IO.Path.GetFileName(hpf.FileName));
                        Response.Write("<b>File: </b>" + hpf.FileName + " <b>Size:</b> " +
                            hpf.ContentLength + " <b>Type:</b> " + hpf.ContentType + " Uploaded Successfully <br/>");
                    }
                }
            }
            catch (Exception ex)
            {

            }
        }

        //protected void btnUploadFiles_Click(object sender, EventArgs e)
        //{
        //}

        private void initPhotoDS()
        {
            dsPhotosFiles.Tables.Add("Photos");
            dsPhotosFiles.Tables[0].Columns.Add("fileBytes", Type.GetType("System.Byte[]"));
            dsPhotosFiles.Tables[0].Columns.Add("filePath");
            dsPhotosFiles.Tables[0].Columns.Add("fileDesc");
            dsPhotosFiles.Tables[0].Columns.Add("id");
        }

        protected void lnkBtnRemovePhoto_Command(object sender, CommandEventArgs e)
        {

            foreach (DataRow dr in dsPhotosFiles.Tables[0].Rows)
            {
                if (dr["id"].ToString() == e.CommandArgument.ToString())
                {
                    dsPhotosFiles.Tables[0].Rows.Remove(dr);
                    break;
                }

            }

            this.bindDataList();
            //lblCurrentFileCount.Text = "Current Files To Upload: " + dsPhotosFiles.Tables[0].Rows.Count;
        }

        //protected void btnAddFile_Click(object sender, EventArgs e)
        //{
           
        //        if (fileUp.PostedFile.ContentLength > 0)
        //        {
        //            //TODO: logic for file extension check
        //            DataRow dr = dsPhotosFiles.Tables[0].NewRow();

        //            string fileExt = System.IO.Path.GetExtension(fileUp.PostedFile.FileName);

        //            byte[] imageBytes = new byte[fileUp.PostedFile.InputStream.Length];
        //            fileUp.PostedFile.InputStream.Read(imageBytes, 0, imageBytes.Length);
        //            string fileName = fileUp.FileName;
        //            fileUp.SaveAs(Server.MapPath("Portfolio/" + fileName));


        //            dr["fileBytes"] = imageBytes;
        //            dr["filePath"] = fileUp.PostedFile.FileName;
        //            dr["fileDesc"] = txtDescImg.Text;
        //            dr["id"] = System.Guid.NewGuid().ToString();

        //            dsPhotosFiles.Tables[0].Rows.Add(dr);
        //        }
            

        //        this.bindDataList();

        //        txtDescImg.Text = "";
        //        lblCurrentFileCount.Text = "Current Files To Upload: " + dsPhotosFiles.Tables[0].Rows.Count;

            
        //}

        protected void ViewCard(object sender, EventArgs e)
        {
            LinkButton lnkVw = sender as LinkButton;
            GridViewRow row = (GridViewRow)lnkVw.Parent.Parent;
            // int locationID = Convert.ToInt32(ddlLocation.SelectedValue);


            int Cid = Convert.ToInt32(gdArtistCard.DataKeys[row.RowIndex]["Artist_Card_Id"]);


            string[] Details = BAL.Customers.Get_Artist_Card_By_Id(Cid);

            GeneratePDF(  Details);

        }

        protected void lnkView_Click(object sender, EventArgs e)
        {
            LinkButton lnkVw = sender as LinkButton;
            GridViewRow row = (GridViewRow)lnkVw.Parent.Parent;
            // int locationID = Convert.ToInt32(ddlLocation.SelectedValue);


            int Cid = Convert.ToInt32(gdArtistCard.DataKeys[row.RowIndex]["Artist_Card_Id"]);


            string[] Details = BAL.Customers.Get_Artist_Card_By_Id(Cid);

            lblViewName.Text = Details[2];
            lblViewLocation.Text = Details[3];
            lblViewType.Text = Details[4];
            lblViewCategory.Text = Details[5];
            lblViewDOB.Text = Details[6];
            lblViewVF.Text = Details[7];
            lblViewVT.Text = Details[8];
            lblViewEMail.Text = Details[9];
            lblViewRefName.Text = Details[10];
            lblVIewRefCon.Text = Details[11];
            lblViewIdProof.Text =  Details[15];
            lblViewAddrProof.Text = Details[16];
            lblViewAmount.Text = Details[17];

            if (Details[22].Equals("Home"))
            {
                lblViewDelTo.Text = "Home : " + Details[23];
            }
            else 
            {
                lblViewDelTo.Text = "Branch";
            }

            int UserId = Cid;
            DataSet Imgs = BAL.Customers.GetImg(UserId);

            if (Imgs.Tables[0].Rows.Count > 0)
            {

                phdImgGallry.Controls.Add(new LiteralControl("<fieldset><legend>Pictures</legend><table><tr>"));

                foreach (DataRow nm in Imgs.Tables[0].Rows)
                {

                    phdImgGallry.Controls.Add(new LiteralControl("<td><a href=\"Portfolio/" + nm["Picture"] + "\"   rel=\"enlargeimage\" rev=\"targetdiv:loadarea2,trigger:mouseover\" target=\"_blank\"  title=\"my caption\"> <img id=\"imagebox\" style=\"width: 50px; height: 40px; border: none;\" alt=\"\" class=\"magnify\" data-magnifyby=\"2\" src=\"Portfolio/" + nm["Picture"] + "\" /></a></td>"));
                }

                phdImgGallry.Controls.Add(new LiteralControl("</tr></table></fieldset>"));
               

            }






            lnkView_ModalPopupExtender.Show();

            //document.getElementById("totalDaystd").innerHTML = "<asp:TextBox ID=\"txtDaysText\" runat=\"server\" ReadOnly=\"True\" Text=\""+ days +"\"></asp:TextBox>";

        }

        protected void btnSearch_Click(object sender, EventArgs e)
        {
            string columnName = cmbSearchHireEquip.SelectedValue, Value = "";


            if (cmbSearchHireEquip.SelectedValue.Equals("0"))
            {
                populateArtistCard();
            }
            else if (cmbSearchHireEquip.SelectedValue.Equals("1"))
            {
                //columnName = "Company_Name";
                Value = txtSrchName.Text;
                DataSet ds = BAL.Customers.SearchArtistCard(columnName, Value);
                gdArtistCard.DataSource = ds;
                gdArtistCard.DataBind();
            }
           
            else if (cmbSearchHireEquip.SelectedValue.Equals("2"))
            {
                //columnName = "Equipment_Location";
                Value = cmbSrchLoc.Text;

                DataSet ds = BAL.Customers.SearchArtistCard(columnName, Value);
                gdArtistCard.DataSource = ds;
                gdArtistCard.DataBind();
            }

          
        }

        protected void lnkEdit_Click(object sender, EventArgs e)
        {
            LinkButton lnkEdit = sender as LinkButton;
            GridViewRow row = (GridViewRow)lnkEdit.Parent.Parent;

            int Cid = Convert.ToInt32(gdArtistCard.DataKeys[row.RowIndex]["Artist_Card_Id"]);
            string[] Details = BAL.Customers.Get_Artist_Card_By_Id(Cid);
            ViewState["Artist_Card_Id"] = Details[0];


            txtEdtName.Text = Details[2];
            cmbEdtLocation.Text = Details[3];
            cmbEdtType.Text = Details[4];
            cmbEdtCategory.Text = Details[5];
            txtEdtBDate.Text = Details[6];
            txtEdtValidFrom.Text = Details[7];
            txtEdtValidTill.Text = Details[8];
            txtEdtEmail.Text = Details[9];
            txtEdtRefName.Text = Details[10];
            txtEdtRefCon.Text = Details[11];
            txtEdtGroup.Text = Details[21];
            LnkEditPopUp.Show();

        }

        protected void lnkDelete_Click(object sender, EventArgs e)
        {
            LinkButton lnkEdit = sender as LinkButton;
            GridViewRow row = (GridViewRow)lnkEdit.Parent.Parent;

            int Cid = Convert.ToInt32(gdArtistCard.DataKeys[row.RowIndex]["Artist_Card_Id"]);
            BAL.Customers.DeleteArtistCardById(Cid);
            populateArtistCard();
        }

        protected void update(object sender, EventArgs e)
        {
            string Name = txtEdtName.Text;
            string Loc = cmbEdtLocation.Text;
            string Addresss = txtEdtGroup.Text;
            string ArtsType = cmbEdtType.Text;
            string Category = cmbEdtCategory.Text;
            string Techni_Type = cmbEdtTechType.Text;
            string Date = txtEdtBDate.Text;
            string Validfrom = txtEdtValidFrom.Text;
            string validTo = txtEdtValidTill.Text;
            string Email = txtEdtEmail.Text;
            string RefName = txtEdtRefName.Text;
            string ContctNo = txtEdtRefCon.Text;
            string ID = ViewState["Artist_Card_Id"].ToString();
            string Group = txtEdtGroup.Text;
         
            BAL.Customers.UpdateArtistCardInfo(Name, Loc, Addresss, ArtsType, Category, Techni_Type, Date, Validfrom, validTo,
                 Email, RefName, ContctNo , ID , Group  );

            populateArtistCard();
        }

        public void populateArtistCard()
        {

            DataSet ds = BAL.Customers.ViewAllArtist_Cards();
            gdArtistCard.DataSource = ds;
            gdArtistCard.DataBind();

        }

        protected void gdArtistCard_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            gdArtistCard.PageIndex = e.NewPageIndex;
            populateArtistCard();
        }

        protected void gdArtistCard_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                LinkButton lEdit = (LinkButton)e.Row.FindControl("lnkEdit");
                Button update = (Button)e.Row.FindControl("btnUpdate");
                LinkButton lDelete = (LinkButton)e.Row.FindControl("lnkDelete");
                lDelete.CommandArgument = e.Row.RowIndex.ToString();
                LinkButton lnkApp = (LinkButton)e.Row.FindControl("lnkApprove");



            }

        }

        public object UserId { get; set; }       

        protected void btnSubmitForm_Click(object sender, EventArgs e)
        {
            string Name = txtName.Text;
            string Loc = cmbLocation.Text;
            string Addresss = txtAddress.Text;
            string ArtsType = cmbType.Text;
            string Category = cmbCategory.Text;
            string Techni_Type = DropDownList1.Text;
            string Date = txtBDate.Text;
            string Validfrom = txtValidFrom.Text;
            string validTo = txtValidTill.Text;
            string Email = txtEmail.Text;
            string RefName = txtRefName.Text;
            string ContctNo = txtRefCon.Text;
            string artistCno = lblArtisCardNo.Text;
            string IDCard = FPhoto.FileName;

            string idProof = cmbIdProof.Text;
            string AddProof = cmbAddressProof.Text;
            string amount = txtAmount.Text;
            string group = txtAddress.Text;
            string delTo = "";
            string PostalAddress = "";

            if (RadioButton1.Checked)
            {
                delTo = "Branch";
            }
            else
            {
                delTo = "Branch";
                PostalAddress = txtPostalAddr.Text;
            }

            int ArtistNo = BAL.Customers.InsertArtistCardInfo(Name, Loc, Addresss, ArtsType, Category, Techni_Type, Date, Validfrom, validTo,
                    Email, RefName, ContctNo, artistCno, IDCard, idProof, AddProof, amount , group , delTo , PostalAddress);
            ViewState["IDArtist"] = ArtistNo;
   FPhoto.SaveAs(Server.MapPath("CustomerPic/" + IDCard));

        }


        protected void clear()
        {
            txtName.Text = "" ;
            cmbLocation.SelectedIndex = 0 ;
            txtAddress.Text = "";
            cmbType.SelectedIndex = 0;
            cmbCategory.SelectedIndex = 0;
            DropDownList1.SelectedIndex = 0;
            txtBDate.Text = "";
            txtValidFrom.Text = "";
            txtValidTill.Text = "";
            txtEmail.Text = "";
            txtRefName.Text = "";
            txtAmount.Text = "";
            txtRefCon.Text = "";           
            cmbIdProof.SelectedIndex = -1;
            cmbAddressProof.SelectedIndex = -1;

            string[] Details = BAL.Customers.GetMaxArtistCardId();

            int genVal = Details[0].ToString().Count();
            int idNo = Convert.ToInt32(Details[0]) + 1;
            string memno = "";

            if (genVal == 1)
            {
                memno = "MN00000" + idNo.ToString();
            }
            else if (genVal == 2)
            {
                memno = "MN0000" + idNo.ToString();
            }
            else if (genVal == 3)
            {
                memno = "MN000" + idNo.ToString();
            }
            else if (genVal == 4)
            {
                memno = "MN00" + idNo.ToString();
            }
            else if (genVal == 5)
            {
                memno = "MN0" + idNo.ToString();
            }
            else if (genVal == 6)
            {
                memno = "MN" + idNo.ToString();
            }

            lblArtisCardNo.Text = memno;
        }

        public void GeneratePDF(string[] Details)
        {





            StringWriter sw = new StringWriter();
            HtmlTextWriter hw = new HtmlTextWriter(sw);

            StringReader sr = new StringReader(sw.ToString());
            Document pdfDoc = new Document(PageSize.A4, 60, 60, 60, 60);
            HTMLWorker htmlparser = new HTMLWorker(pdfDoc);

            PdfWriter.GetInstance(pdfDoc, new FileStream(Server.MapPath("~/IdCards/" + string.Format("Card-{0}.pdf", Details[0])), FileMode.Create, FileAccess.Write));

            string notice = "Help Line : +91 22 256 77777";
           // string ToInvoice = Address;
            string contents = File.ReadAllText(Server.MapPath("~/Card.htm"));

            contents = contents.Replace("[NAME]", Details[2]);
            contents = contents.Replace("[ARTISTGROUP]", Details[5]);
            contents = contents.Replace("[ARTISTCATEGORY]", Details[5]);
            contents = contents.Replace("[DOB]",DateTime.Parse(Details[6]).ToShortDateString());
            contents = contents.Replace("[GENDER]", Details[4]);
            contents = contents.Replace("[VALIDFROM]", DateTime.Parse( Details[7]).ToShortDateString());
            DateTime dt = new DateTime();
            dt = DateTime.Parse( Details[7]);
            int day = dt.Day ;
            int mon = dt.Month ;
            int yr = dt.Year + 1 ;
            DateTime vd = new DateTime(yr , mon  , day );

            contents = contents.Replace("[VALIDTILL]", vd.ToShortDateString());

            int genVal = Details[0].ToString().Count();
            string memno = "" ;

            if (genVal == 1)
            {
                memno = "MN00000" + Details[0].ToString();
            }
            else if (genVal == 2)
            {
                memno = "MN0000" + Details[0].ToString();
            }
            else if (genVal == 3)
            {
                memno = "MN000" + Details[0].ToString();
            }
            else if (genVal == 4)
            {
                memno = "MN00" + Details[0].ToString();
            }
            else if (genVal == 5)
            {
                memno = "MN0" + Details[0].ToString();
            }
            else if (genVal == 6)
            {
                memno = "MN" + Details[0].ToString();
            }

            contents = contents.Replace("[MEMBERSHIPNO]", memno);
          

            // Step 4: Parse the HTML string into a collection of elements...

            pdfDoc.Open();



            var logo = iTextSharp.text.Image.GetInstance(Server.MapPath("~/Images/candy-gloss.png"));
            logo.SetAbsolutePosition(100, 770);
            logo.ScaleAbsolute( 450 , 70);
            

            pdfDoc.Add(logo);
            var IDimage = iTextSharp.text.Image.GetInstance(Server.MapPath("~/Images/" + Details[14] +""));
            //var IDimage = iTextSharp.text.Image.GetInstance(Server.MapPath("~/Images/idimag.jpg"));
            logo.SetAbsolutePosition(110,630);
            logo.ScaleAbsolute(140, 120);
            pdfDoc.Add(logo);
            var parsedHtmlElements = HTMLWorker.ParseToList(new StringReader(contents), null);

            // pdfDoc.HtmlStyleClass = "table";

            foreach (var htmlElement in parsedHtmlElements)
            {
                pdfDoc.Add(htmlElement as IElement);
            }

            htmlparser.Parse(sr);
            
           pdfDoc.Close();

           string path = "~/IdCards/" + string.Format("Card-{0}.pdf", Details[0]);

           Response.Redirect(path);

        }

        protected void btnUploadFiles_Click1(object sender, EventArgs e)
        {

            string Name = txtName.Text;
            string Loc = cmbLocation.Text;
            string Addresss = txtAddress.Text;
            string ArtsType = cmbType.Text;
            string Category = cmbCategory.Text;
            string Techni_Type = DropDownList1.Text;
            string Date = txtBDate.Text;
            string Validfrom = txtValidFrom.Text;
            string validTo = txtValidTill.Text;
            string Email = txtEmail.Text;
            string RefName = txtRefName.Text;
            string ContctNo = txtRefCon.Text;
            string artistCno = lblArtisCardNo.Text;
            string IDCard = FPhoto.FileName;
            string idProof = cmbIdProof.Text;
            string AddProof = cmbAddressProof.Text;
            string Amount = txtAmount.Text;
            string group = txtAddress.Text;
            string delTo = "";
            string PostalAddress = "";

            if (RadioButton1.Checked)
            {
                delTo = "Branch";
            }
            else
            {
                delTo = "Branch";
                PostalAddress = txtPostalAddr.Text;
            }

            int ArtistNo = BAL.Customers.InsertArtistCardInfo(Name, Loc, Addresss, ArtsType, Category, Techni_Type, Date, Validfrom, validTo,
                    Email, RefName, ContctNo, artistCno, IDCard, idProof, AddProof, Amount, group , delTo , PostalAddress);
            ViewState["IDArtist"] = ArtistNo;




            //if (cmbCategory.Text.Equals("Artist"))
            //{

            //    try
            //    {
            //        for (int i = 0; i < dsPhotosFiles.Tables[0].Rows.Count; i++)
            //        {
            //            //TODO:logic to save image path and description to database

            //            string fileName = System.IO.Path.GetFileName(dsPhotosFiles.Tables[0].Rows[i]["filePath"].ToString());



            //            byte[] imageBytes;
            //            imageBytes = (byte[])dsPhotosFiles.Tables[0].Rows[i]["fileBytes"];
            //            int useri_id = Convert.ToInt32(ViewState["IDArtist"]);
            //            // string Descr = txtDescr.Text;
            //            //   string rate = "100";
            //            // string qty = txtQty.Text;
            //            string DescrImg = dsPhotosFiles.Tables[0].Rows[i]["fileDesc"].ToString();
            //            //int OrderId = BAL.Service.GetOrderID(useri_id, Descr, rate, qty);





            //            //their is no uploading..just writing out the bytes to the directory on the web server.
            //            //  System.IO.File.WriteAllBytes(Server.MapPath(string.Format("~/documents/{0}", fileName)), imageBytes);

            //            BAL.Customers.UploadImages(fileName, useri_id, DescrImg);
            //            idSpanPortImage.Style.Add("display", "block");
            //            idSpanPortImage.InnerHtml = "Image(s) inserted Successfully";
            //            // viewImage.Visible = true;
            //            // UploadImage.Visible = false;
            //            ///GetImages(OrderId);


            //        }

            //        //TODO: show success message logic

            //        //clear out rows of dataset not the whole dataset
            //        dsPhotosFiles.Tables[0].Rows.Clear();
            //        this.bindDataList();
            //        lblCurrentFileCount.Text = "Current Files To Upload: " + "0";




            //    }
            //    catch (Exception ex)
            //    {
            //        //TODO: show error message of which file did not get uploaded
            //        throw new Exception(ex.Message);
            //    }
            //}


            clear();
            spnMsg.Visible = true;
            spnText.InnerHtml = "Your details have been submitted.";
            populateArtistCard();
        }
    }
}